//
//  MoneyChangeVC.m
//  PearRich
//
//  Created by Jinniu on 2020/4/2.
//  Copyright © 2020 谢黎鹏. All rights reserved.
//

#import "MoneyChangeVC.h"
#import "MoneyChangeCell.h"
#import <TFHpple/TFHpple.h>
typedef void (^GetDataBlock)(NSString * rate);
@interface MoneyChangeVC ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,retain)UITableView * myTab;
@property(nonatomic,retain)NSMutableArray * dataArr;
@property(nonatomic,retain)NSMutableDictionary * mainDic;
@property(nonatomic,assign)NSInteger count;
@end

@implementation MoneyChangeVC
//https://hq.sinajs.cn/result.js?list=CNYJPY
//http://api.k780.com/?app=finance.rate&scur=CNY&tcur=KRW&appkey=48805&sign=24d2eef36c6a081360a7ab1b3c11e7d2&format=json
- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTitle = @"汇率换算";
    self.mainDic = [NSMutableDictionary new];
    self.dataArr = [NSMutableArray new];
    NSArray * nameArr = @[@"人民币",@"美元",@"日元",@"韩元",@"港币",@"新台币",@"英镑",@"欧元",@"泰铢"];
    NSArray * keyArr = @[@"RMB",@"USD",@"JPY",@"KRW",@"HKD",@"TWD",@"GBP",@"EUR",@"THB"];
    [self.mainDic setObject:@"1" forKey:@"人民币"];
    for (int i =0;i<nameArr.count ; i++) {
        MoneyChangeModel * mo = [MoneyChangeModel new];
        mo.name = nameArr[i];
        mo.key = keyArr[i];
        [self.dataArr addObject:mo];
    }
    [self createUI];
    
    BOOL hasEmpty = NO;
    NSUserDefaults * def = [NSUserDefaults standardUserDefaults];
    for (NSString * key in keyArr) {
        if (![key isEqualToString:@"RMB"]) {
            NSString * val = [def objectForKey:key];
            if (val.length == 0) {
                [self getData];
                hasEmpty = YES;
                break;
            }
        }
    }
    if (!hasEmpty) {
        [self configReqDb];
    }
}
-(void)configReqDb{
    [self.mainDic setObject:@"1" forKey:@"人民币"];
    [self.mainDic setObject:[DLUserDefaultModel userDefaultsModel].USD forKey:@"美元"];
    [self.mainDic setObject:[DLUserDefaultModel userDefaultsModel].JPY forKey:@"日元"];
    [self.mainDic setObject:[DLUserDefaultModel userDefaultsModel].KRW forKey:@"韩元"];
    [self.mainDic setObject:[DLUserDefaultModel userDefaultsModel].HKD forKey:@"港币"];
    [self.mainDic setObject:[DLUserDefaultModel userDefaultsModel].TWD forKey:@"新台币"];
    [self.mainDic setObject:[DLUserDefaultModel userDefaultsModel].GBP forKey:@"英镑"];
    [self.mainDic setObject:[DLUserDefaultModel userDefaultsModel].EUR forKey:@"欧元"];
    [self.mainDic setObject:[DLUserDefaultModel userDefaultsModel].THB forKey:@"泰铢"];
    NSArray * keyArr = @[@"RMB",@"USD",@"JPY",@"KRW",@"HKD",@"TWD",@"GBP",@"EUR",@"THB"];
    for (int i=0;i<self.dataArr.count;i++) {
        MoneyChangeModel * mo = self.dataArr[i];
        NSString * key = keyArr[i];
        if ([mo.key isEqualToString:key] && ![key isEqualToString:@"RMB"]) {
            NSString * rate = [[NSUserDefaults standardUserDefaults]objectForKey:key];
            mo.num = rate;
        }
    }
}
-(void)getData{
    [QMUITips showLoadingInView:self.view];
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [queue addOperationWithBlock:^{
        [self requestMethodCountry2:@"USD" block:^(NSString *rate) {
            [self reqSetKey:@"美元" rate:rate];
            [DLUserDefaultModel userDefaultsModel].USD = rate;
        }];
    }];
    [queue addOperationWithBlock:^{
        [self requestMethodCountry2:@"JPY" block:^(NSString *rate) {
            [self reqSetKey:@"日元" rate:rate];
            [DLUserDefaultModel userDefaultsModel].JPY = rate;
        }];
    }];
    [queue addOperationWithBlock:^{
        [self requestMethodCountry2:@"KRW" block:^(NSString *rate) {
            [self reqSetKey:@"韩元" rate:rate];
            [DLUserDefaultModel userDefaultsModel].KRW = rate;
        }];
    }];
    [queue addOperationWithBlock:^{
        [self requestMethodCountry2:@"HKD" block:^(NSString *rate) {
            [self reqSetKey:@"港币" rate:rate];
            [DLUserDefaultModel userDefaultsModel].HKD = rate;
        }];
    }];
    [queue addOperationWithBlock:^{
        [self requestMethodCountry2:@"TWD" block:^(NSString *rate) {
            [self reqSetKey:@"新台币" rate:rate];
            [DLUserDefaultModel userDefaultsModel].TWD = rate;
        }];
    }];
    [queue addOperationWithBlock:^{
        [self requestMethodCountry2:@"GBP" block:^(NSString *rate) {
            [self reqSetKey:@"英镑" rate:rate];
            [DLUserDefaultModel userDefaultsModel].GBP = rate;
        }];
    }];
    [queue addOperationWithBlock:^{
        [self requestMethodCountry2:@"EUR" block:^(NSString *rate) {
            [self reqSetKey:@"欧元" rate:rate];
            [DLUserDefaultModel userDefaultsModel].EUR = rate;
        }];
    }];
    [queue addOperationWithBlock:^{
        [self requestMethodCountry2:@"THB" block:^(NSString *rate) {
            [self reqSetKey:@"泰铢" rate:rate];
            [DLUserDefaultModel userDefaultsModel].THB = rate;
        }];
    }];
}
-(void)reqSetKey:(NSString*)name rate:(NSString*)rate{
    [self.mainDic setObject:rate forKey:name];
    self.count ++ ;
    for (MoneyChangeModel * mo in self.dataArr) {
        if ([mo.name isEqualToString:name]) {
            mo.num = rate;
        }
    }
    if (self.count == 8) {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [QMUITips hideAllTips];
            [self.myTab reloadData];
        }];        
    }
}
-(void)requestMethodCountry2:(NSString*)country2 block:(GetDataBlock)block{
    NSString * url = [NSString stringWithFormat:@"http://www.webmasterhome.cn/huilv/CNY/CNY%@",country2];
//    NSString *htmlString = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:nil];
//    NSLog(@"%@",htmlString);
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    TFHpple * doc       = [[TFHpple alloc] initWithHTMLData:data];
    NSArray * elements  = [doc searchWithXPathQuery:@"//div[@class='rowright']"];
    if (elements.count > 0) {
        BOOL isFind = NO;
        for (TFHppleElement * element in elements) {
            if (element.text.length > 0 && [Mytools isPureFloat:element.text]) {
                NSLog(@"%@,%@,",country2,element.text);
                block(element.text);
                isFind = YES;
                break;
            }
        }
        if (!isFind) {
            NSArray * elementsSpan  = [doc searchWithXPathQuery:@"//span[@class='mexl']"];
            if (elementsSpan.count > 0) {
                BOOL isFind = NO;
                for (TFHppleElement * element in elementsSpan) {
                    if (element.text.length > 0 && [Mytools isPureFloat:element.text]) {
                        NSLog(@"%@,%@,",country2,element.text);
                        block(element.text);
                        isFind = YES;
                        break;
                    }
                }
            }
        }
    }
}
-(void)createUI{
    self.myTab = [[UITableView alloc]initWithFrame:Frame(0, kTopHeight, IPHONE_WIDTH, IPHONE_HEIGHT - kTopHeight - KTabbarSafeBottomMargin) style:UITableViewStyleGrouped];
    self.myTab.delegate = self;
    self.myTab.dataSource = self;
    self.myTab.rowHeight = 60;
    [self.view addSubview:self.myTab];
}
#pragma mark tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MoneyChangeCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell = [[MoneyChangeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.model = self.dataArr[indexPath.row];
    cell.changeBlock = ^(NSString * _Nonnull str ,NSString * _Nonnull rate) {
        for (NSInteger i=0; i<self.dataArr.count; i++) {
            if (indexPath.row !=i) {
                NSIndexPath *idx = [NSIndexPath indexPathForRow:i inSection:0];
                MoneyChangeCell * cp = [tableView cellForRowAtIndexPath:idx];
                NSString * value = self.mainDic[cp.nameLab.text];
                float val = [str floatValue] * (1/[rate floatValue]) *  [value floatValue];
                [cp setValue:[NSString stringWithFormat:@"%f",val] forKeyPath:@"_inpuTF.text"];
            }
        }
    };
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel * descLab = [UILabel labelWithTitle:@"  选一个输入看看~" color:[UIColor colorWithHue:0.01 saturation:0.33 brightness:0.94 alpha:1] fontSize:14 alignment:NSTextAlignmentLeft];
    descLab.backgroundColor = [UIColor colorWithHue:0.02 saturation:0.1 brightness:0.98 alpha:1];
    
    return  descLab;
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

@end
